package com.nowcoder.code.lcof;

import java.util.ArrayList;

public class JZ29 {

    public static void main(String[] args) {
        int[][] is = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
        System.out.println(new JZ29().printMatrix(is));
    }

    ArrayList<Integer> arrayList;
    int[][] matrix;

    public ArrayList<Integer> printMatrix(int[][] matrix) {

        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new ArrayList<>();
        }

        arrayList = new ArrayList<>(matrix.length * matrix[0].length);
        this.matrix = matrix;
        right(0, 0);
        return arrayList;
    }


    public void right(int i, int j) {
        arrayList.add(matrix[i][j]);
        matrix[i][j] = -1;
        if (j + 1 < matrix[0].length && matrix[i][j + 1] != -1) {
            right(i, j + 1);
        } else if (i + 1 < matrix.length && matrix[i + 1][j] != -1) {
            down(i + 1, j);
        }

    }

    public void down(int i, int j) {
        arrayList.add(matrix[i][j]);
        matrix[i][j] = -1;
        if (i + 1 < matrix.length && matrix[i + 1][j] != -1) {
            down(i + 1, j);
        } else if (j - 1 >= 0 && matrix[i][j - 1] != -1) {
            left(i, j - 1);
        }

    }


    public void left(int i, int j) {
        arrayList.add(matrix[i][j]);
        matrix[i][j] = -1;
        if (j - 1 >= 0 && matrix[i][j - 1] != -1) {
            left(i, j - 1);
        } else if (i - 1 >= 0 && matrix[i - 1][j] != -1) {
            up(i - 1, j);
        }
    }

    public void up(int i, int j) {
        arrayList.add(matrix[i][j]);
        matrix[i][j] = -1;
        if (i - 1 >= 0 && matrix[i - 1][j] != -1) {
            up(i - 1, j);
        } else if (j + 1 < matrix[0].length && matrix[i][j + 1] != -1) {
            right(i, j + 1);
        }
    }


}
